﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Borg
{
    public class RepositoryCollection<T> : ReadOnlyCollection<T>
        where T : RepositoryElement
    {
        public T this[string name]
        {
            get { return Items.FirstOrDefault(item => item.Name == name); }
        }

        public RepositoryCollection(IList<T> list)
            : base(list)
        { }

        public bool Contains(string name)
        {
            return this[name] != null;
        }

        public T Find(int id)
        {
            return Items.FirstOrDefault(item => item.id == id);
        }

        public T[] Find(string name)
        {
            return Items.Where(item => item.Name == name).ToArray();
        }

        public T[] ToArray()
        {
            return ((List<T>)Items).ToArray();
        }

        public override string ToString()
        {
            var builder = new StringBuilder();

            foreach (var obj in Items)
            {
                if (builder.Length > 0)
                    builder.AppendLine();

                builder.Append(obj);
            }

            return builder.ToString();
        }

        internal void Add(T item)
        {
            Items.Add(item);
        }

        internal bool Remove(T item)
        {
            return Items.Remove(item);
        }

        internal void RemoveAt(int index)
        {
            Items.RemoveAt(index);
        }

        internal void AddRange(IEnumerable<T> items)
        {
            foreach (var obj in items)
                Items.Add(obj);
        }

        internal void Clear()
        {
            Items.Clear();
        }
    }
}

